package com.ruoyi.system.outto.game.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.model.domain.AccountInfo;
import com.ruoyi.system.model.domain.AccountLable;
import com.ruoyi.system.model.domain.InfoImg;
import com.ruoyi.system.model.domain.SalePartner;
import com.ruoyi.system.model.mapper.AccountLableMapper;
import com.ruoyi.system.model.mapper.InfoImgMapper;
import com.ruoyi.system.outto.core.LCConstant;
import com.ruoyi.system.outto.core.MapUntils;
import com.ruoyi.system.outto.core.OutUrlConstant;
import com.ruoyi.system.outto.game.CommonApi;
import com.ruoyi.system.outto.game.IKGAPI;
import com.ruoyi.system.outto.game.IYZJAPI;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author sdq
 * @Date 2022/8/31 22:28
 */
@Slf4j
@Service
public class YZJAPIImpl implements IYZJAPI {
    @Resource
    private InfoImgMapper infoImgMapper;
    @Value("${desc.title}")
    private String descTitle;
    @Autowired
    private CommonApi commonApi;

    @Resource
    private AccountLableMapper accountLableMapper;

    private SalePartner sa;
    private static String YZJURL = null;

    private Map<String,Object> params(AccountInfo accountInfo, Long userId){

        YZJURL = sa.getOther();
        Map<String,Object> params = new TreeMap<>();
        params.put("game_code",accountInfo.getId().toString());//账号编号
        params.put("game_type","9");//游戏类型ID（固定9）
        if (StringUtils.isEmpty(accountInfo.getCampId())){
            params.put("camp_id","11111");//营地号
        }else {
            params.put("camp_id",accountInfo.getCampId());//营地号
        }

        params.put("account_number",descTitle+accountInfo.getId());
        if (Objects.equals("王者荣耀",accountInfo.getType())){
            params.put("hero_num",null == accountInfo.getHeroes()?"0":accountInfo.getHeroes().toString());//英雄数量/套装数量
            params.put("skin_num",null == accountInfo.getSkins()?"0":accountInfo.getSkins().toString());//皮肤数量/枪皮数量
        }else {
            params.put("hero_num",null == accountInfo.getSuit()?"0":accountInfo.getSuit().toString());//英雄数量/套装数量
            params.put("skin_num",null == accountInfo.getGuns()?"0":accountInfo.getGuns().toString());//皮肤数量/枪皮数量
        }
        params.put("attrData","---");
        AccountLable accountLable = new AccountLable();
        accountLable.setInfoId(accountInfo.getId());
        List<AccountLable> accountLables = accountLableMapper.selectAccountLableList(accountLable);
        if (!CollectionUtils.isEmpty(accountLables)){
            List<String> collect = accountLables.stream().map(lable -> lable.getLable()).collect(Collectors.toList());
            String attrData = collect.stream().map(String::valueOf).collect(Collectors.joining(","));
            params.put("attrData",attrData);
        }

        if (Arrays.asList(LCConstant.haveTwoList).contains(accountInfo.getLevel()) || Objects.equals(accountInfo.getLevel(),LCConstant.bakFace)){
            params.put("ercixiugai","Y");
        }
        if (Objects.equals(accountInfo.getLevel(), LCConstant.rezhengMial)){
            params.put("ercixiugai","Y");
        }
        if (Objects.equals(accountInfo.getLevel(), LCConstant.noTwo)){
            params.put("ercixiugai","N");
        }
        if (Objects.equals(accountInfo.getLevel(), LCConstant.noMial)){
            params.put("ercixiugai","N");
        }

        params.put("title","【"+descTitle + "_" + accountInfo.getId() + "】  "+ accountInfo.getLevel() + "  " + accountInfo.getDes());
        InfoImg infoImg = new InfoImg();
        infoImg.setInfoId(accountInfo.getId());
        infoImg.setType(Constants.STR_1);
        List<InfoImg> infoImgs = infoImgMapper.selectInfoImgList(infoImg);
        if(!CollectionUtils.isEmpty(infoImgs)){
            params.put("images",infoImgs.stream().map(InfoImg::getImgUrl).collect(Collectors.joining(",")));
        }
        params.put("game_img",accountInfo.getTitleImg());

        if(accountInfo.getRegional().endsWith("Q")){
            params.put("game_account_type","1");//账号类型（1 QQ 2 微信）
        }else{
            params.put("game_account_type","2");//账号类型（1 QQ 2 微信）
        }
        if(accountInfo.getRegional().startsWith("安卓")){
            params.put("is_system","1");//操作系统（1 安卓 2 苹果）
        }else{
            params.put("is_system","2");//操作系统（1 安卓 2 苹果）
        }
        params.put("game_region","1");//游戏大区
        params.put("inscription_num","1");//五级铭文数量/载具数量
        BigDecimal bigDecimal = commonApi.addPrice(accountInfo.getPrice(), sa.getSeleep());
        commonApi.setPrice(bigDecimal,accountInfo.getId(),sa);
        params.put("game_sell_price",bigDecimal.stripTrailingZeros().toPlainString());//销售价
        //1王者荣耀; 2原神; 3和平精英;4吃鸡
        if("王者荣耀".equals(accountInfo.getType())){
            params.put("game_id","10");//游戏名称ID（王者10，吃鸡11）
        }else if("和平精英".equals(accountInfo.getType())){
            params.put("game_id","11");//游戏名称ID（王者10，吃鸡11）
        }else{
            throw new GlobalException("暂不支持此游戏");
        }
        //以上 计算key
        String str = getCover(params) + "key=" +sa.getSaleKey();
        log.info("加密前请求参数={}",str);
        String sign = DigestUtils.md5Hex(str).toUpperCase();
        params.put("signKey",sign);

        params.put("userId",sa.getTwoOther());
        return params;
    }
    @Override
    public AjaxResult addGame(AccountInfo accountInfo, Long userId, SalePartner salePartner) {
        try{
            this.sa = salePartner;
            Map<String, Object> result = new HashMap<>();
            Map<String, Object> params = params(accountInfo,userId);
            params.put("pg","apiAddGame");
            String paramsStr = JSONObject.toJSONString(params);
            log.info("游之境新增请求参数={}",paramsStr);
            String response = "";
            if (!Objects.isNull(YZJURL)){
                response = HttpUtils.doPostForm(YZJURL, params, null);
            }

            log.info("游之境新增返回参数={}",response);
            JSONObject resultJson = JSONObject.parseObject(response);
            String msg = resultJson.getString("msg");
            msg = MapUntils.unicodeToString(msg);
            if (!(1 == resultJson.getInteger("code"))){
                result.put("code",500);
            }else {
                result.put("code",200);
            }
            result.put("req",JSONObject.toJSONString(params));
            result.put("res",response);
            result.put("msg",msg);
            return AjaxResult.success(result);
        }catch (Exception e){
            throw new GlobalException(e.getMessage());
        }
    }

    @Override
    public AjaxResult editGame(AccountInfo accountInfo, Long userId, SalePartner salePartner) {
        try{
            this.sa = salePartner;
            YZJURL = sa.getOther();
            Map<String, Object> result = new HashMap<>();
            Map<String, Object> params = params(accountInfo,userId);
            params.put("pg","apiUpdGame");
            String paramsStr = JSONObject.toJSONString(params);
            log.info("游之境修改请求参数={}",paramsStr);
            String response = "";
            if (!Objects.isNull(YZJURL)){
                response = HttpUtils.doPostForm(YZJURL, params, null);
            }

            log.info("游之境修改返回参数={}",response);
            JSONObject resultJson = JSONObject.parseObject(response);
            String msg = resultJson.getString("msg");
            msg = MapUntils.unicodeToString(msg);
            if (!(1 == resultJson.getInteger("code"))){
                result.put("code",500);
            }else {
                result.put("code",200);
            }
            result.put("req",JSONObject.toJSONString(params));
            result.put("res",response);
            result.put("msg",msg);
            return AjaxResult.success(result);
        }catch (Exception e){
            throw new GlobalException(e.getMessage());
        }
    }

    @Override
    public AjaxResult delGame(AccountInfo accountInfo, Long userId, SalePartner sa) {
        try{
            YZJURL = sa.getOther();
            Map<String, Object> result = new HashMap<>();
            Map<String, String> params = new HashMap<>();
            params.put("pg","apiDelGame");
            params.put("userId",sa.getTwoOther());
            params.put("game_code",accountInfo.getId().toString());
            String sign = DigestUtils.md5Hex("game_code="+ params.get("game_code")+ "&key=" +sa.getSaleKey()).toUpperCase();
            params.put("sign",sign);
//            String paramsStr = JSONObject.toJSONString(params);
            String paramsStr = "pg=apiDelGame&userId=" + sa.getTwoOther() + "&game_code="+accountInfo.getId().toString()+"&signKey="+sign;
            log.info("游之境删除请求参数={}",paramsStr);
            String response = "";
            if (!Objects.isNull(YZJURL)){
//                response = HttpUtils.sendPost(KGURL, paramsStr, "application/json");
                response = HttpUtils.sendGet(YZJURL, paramsStr);
            }

            log.info("游之境删除返回参数={}",response);
            JSONObject resultJson = JSONObject.parseObject(response);
            String msg = resultJson.getString("msg");
            msg = MapUntils.unicodeToString(msg);
            if (!(1 == resultJson.getInteger("code"))){
                result.put("code",500);
            }else {
                result.put("code",200);
            }
            result.put("req",JSONObject.toJSONString(params));
            result.put("res",response);
            result.put("msg",msg);
            return AjaxResult.success(result);
        }catch (Exception e){
            throw new GlobalException(e.getMessage());
        }
    }

    public static String getCover(Map<String,Object> params){
        StringBuffer resut = new StringBuffer();
        for (String key : params.keySet()) {
            if(params.get(key) instanceof String && StringUtils.isNotEmpty((String)params.get(key))){
                resut.append(key+"="+params.get(key)+"&");
            }
            if(params.get(key) instanceof Boolean){
                resut.append(key+"="+params.get(key)+"&");
            }
            if(params.get(key) instanceof Long){
                resut.append(key+"="+params.get(key)+"&");
            }
            if(params.get(key) instanceof Integer && null != params.get(key)){
                resut.append(key+"="+params.get(key)+"&");
            }
        }
        return resut.toString();
    }

    public static void main(String[] args) {
//-------------------新增-------------------------
//        Map<String,Object> params = new TreeMap<>();
//        params.put("game_code","test");
//        params.put("game_type","9");//游戏类型ID（固定9）
//        params.put("game_id","10");//游戏名称ID（王者10，吃鸡11）
//        params.put("camp_id","198");//营地号
//        params.put("account_number","1");
//        params.put("hero_num","200");//英雄数量/套装数量
//        params.put("skin_num","100");//皮肤数量/枪皮数量
//        params.put("title","title");
//        params.put("images","1");
//        params.put("game_img","1");
//        params.put("game_account_type","1");//账号类型（1 QQ 2 微信）
//        params.put("is_system","1");//操作系统（1 安卓 2 苹果）
//        params.put("game_region","1");//游戏大区
//        params.put("inscription_num","1");//五级铭文数量/载具数量
//        params.put("game_sell_price","188");//销售价
//
//        //以上 计算key
//        String str = getCover(params) + "key="+"n5je6zli5425c24yz60js59lfx236o51231" ;
//        System.out.println("signStr : "+str);
//        String sign = DigestUtils.md5Hex(str).toUpperCase();
//        System.out.println("sign: "+sign);
//        params.put("signKey",sign);
//
//        params.put("pg","apiAddGame");
//        params.put("userId","5");
//
//
//        System.out.println(JSONObject.toJSONString(params));
//        String baseUrl = "http://www.kaigewangyou.com/api/api.php";
//        String response = HttpUtils.doPostForm(baseUrl, params, null);
//        System.out.println(response);
//        JSONObject resultJson = JSONObject.parseObject(response);
//        String msg = resultJson.getString("msg");
//        System.out.println(msg);

        //------修改
        Map<String,Object> params = new TreeMap<>();
        params.put("game_code","test");
        params.put("game_type","9");//游戏类型ID（固定9）
        params.put("camp_id","198");//营地号
        params.put("account_number","1");
        params.put("hero_num","200");//英雄数量/套装数量
        params.put("skin_num","100");//皮肤数量/枪皮数量
        params.put("title","title");
        params.put("images","http://oss.p74.cn/5/2021/04/09/1617973327139.jpg");
        params.put("game_img","http://oss.p74.cn/5/2021/04/09/1617973327139.jpg");
        params.put("game_account_type","1");//账号类型（1 QQ 2 微信）
        params.put("is_system","1");//操作系统（1 安卓 2 苹果）
        params.put("game_region","1");//游戏大区
        params.put("inscription_num","1");//五级铭文数量/载具数量
        params.put("game_sell_price","188");//销售价
        params.put("game_id","10");//游戏名称ID（王者10，吃鸡11）
        //以上 计算key
        String str = getCover(params) + "key=" + "n5je6zli5425c24yz60js59lfx236o51231";
        String sign = DigestUtils.md5Hex(str).toUpperCase();
        params.put("signKey",sign);

        params.put("userId","5");
        params.put("pg","apiUpdGame");

        System.out.println(JSONObject.toJSONString(params));
        String baseUrl = "http://www.kaigewangyou.com/api/api.php";
        String response = HttpUtils.doPostForm(baseUrl, params, null);
        JSONObject resultJson = JSONObject.parseObject(response);
        String msg = resultJson.getString("msg");
        System.out.println(msg);

    }
}
